﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using LuctecWS.DAL;
using System.Runtime.Serialization;
using System.Data;
using LuctecWS.Aspect;

namespace LuctecWS.Core
{
    [DataContract]
    public class Contact : Base
    {
        [DataMember]
        public int Id { get; set; }
        [DataMember]
        public string Name { get; set; }
        [DataMember]
        public string Email { get; set; }
        [DataMember]
        public bool Active { get; set; }

        [LogException]
        public Contact Save()
        {
            using (LuctecEntities context = new LuctecEntities())
            {
                if (Id == 0)
                {
                    var contact = new contacts() { Active = true, Email = this.Email, Name = this.Name, Id = this.Id };

                    context.AddObject("contacts", contact);
                }
                else
                {
                    var contact = context.contacts.First(c => c.Id == Id);

                    contact.Name = Name;
                    contact.Email = Email;
                    contact.Active = Active;
                }

                context.SaveChanges();

                if(Id == 0)
                    return AdaptDBCore(context.contacts.ToList().Last());
                else
                    return AdaptDBCore(context.contacts.ToList().First(c => c.Id == Id));
            }
        }

        [LogException]
        public static List<Contact> GetContacts()
        {
            using (LuctecEntities context = new LuctecEntities())
            {
                var dbContacts = context.contacts.ToList();

                return AdaptDBCore(dbContacts);
            }
        }

        [LogException]
        private static List<Contact> AdaptDBCore(List<contacts> dbContacts)
        {
            List<Contact> contacts = new List<Contact>();

            if (dbContacts != null)
                foreach (var dbContact in dbContacts)
                {
                    Contact contact = AdaptDBCore(dbContact);

                    if (contact != null)
                        contacts.Add(contact);
                }

            return contacts;
        }

        [LogException]
        private static Contact AdaptDBCore(contacts dbContact)
        {
            if (dbContact != null)
                return new Contact() { Active = dbContact.Active, Email = dbContact.Email, Id = dbContact.Id, Name = dbContact.Name };

            return null;
        }
    }
}